package com.baiyue.controller;

import com.baiyue.annotation.SystemLog;
import com.baiyue.entity.UserEntity;
import com.baiyue.enums.LogType;
import com.baiyue.model.user.LoginDataRequest;
import com.baiyue.result.Result;
import com.baiyue.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author wubo
 */
@RestController
@RequestMapping(value = "/api")
public class LoginController {

    @Resource
    private UserService userService;


    @Autowired
    private HttpServletRequest request;
    /**
     * 登录功能
     * 验证用户名和密码，登录成功，生成token，存入到redis中
     * 登录成功
     *
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    @SystemLog(description = "用户登录",type = LogType.LOGIN)
    public Result<String> doLogin(@RequestBody LoginDataRequest request) {
        //用户登录逻辑，返回token
        String token = userService.login(request);
        return Result.success(token);
    }

    /**
     * 退出当前登录用户
     * @return
     */
    @SystemLog(description = "退出登录",type = LogType.OPERATION)
    @PostMapping("/signOut")
    public Result<Boolean> signOut(){
        userService.signOut();
        return Result.success(true);
    }

    /**
     * 获取当前token 是否已经过期，如果没有过期则直接跳转
     * @return
     */
    @PostMapping("/getLogged")
    public Result<Boolean> logged(){
        userService.logged();
        return Result.success(true);
    }

    /**
     * 切换用户
     * @param user 传参账号密码
     * @return 返回字符串
     */
    @SystemLog(description = "切换用户",type = LogType.OPERATION)
    @PostMapping("/switchUser")
    public Result<String> switchUser(@RequestBody UserEntity user){
        String token = userService.switchUser(user.getUsername(),user.getPassword());
        return Result.success(token);
    }

    /**
     * 获取当前登录用户
     * @return 返回实体类 UserEntity
     */
    @PostMapping("/getUser")
    public Result<UserEntity> getLoginUser(){
        return Result.success(userService.getLoginUser(request));
    }
}
